#!/bin/sh
# Copyright (C) 2006 OpenWrt.org
# Copyright (C) 2010 Vertical Communications


do_disk_ready() {
	diskpart=`fdisk -l /dev/sda | grep '^/dev/sda[0-9]' | wc -l`
	[ "x$diskpart" = "x4" ] || {
		disksize="`fdisk -l /dev/sda | grep '/dev/sda:' | head -n1 | awk '{print $5}'`"
		test -n "$disksize" || return
		# <= 2GiB && return
		test $disksize -le 2147483648 && return

		echo -ne 'd\n4\nw\n' | fdisk /dev/sda
		echo -ne 'd\n3\nw\n' | fdisk /dev/sda
		# [_boot_|_rootfs_...1G...][cfg 1G][data...]
		echo -ne 'n\np\n3\n1835008\n3932160\nn\np\n3932672\n\nw\n' | fdisk /dev/sda
		partx -a /dev/sda
		test -b /dev/sda3 -a -b /dev/sda4  || {
			MAJOR="`ls -l /dev/sda2 | grep '/dev/sda2' | awk '{print $5}' | grep -o '[0-9]*'`"
			test -n "$MAJOR" && {
				rm -f /dev/sda3
				mknod /dev/sda3 b $MAJOR 3
				rm -f /dev/sda4
				mknod /dev/sda4 b $MAJOR 4
			}
		}
		test -b /dev/sda3 && echo erase >/dev/sda3
		test -b /dev/sda4 && echo erase >/dev/sda4
	}
	test -b /dev/sda3 && [ "x`head -c5 /dev/sda3`" = "xerase" ] && {
		echo -ne 'y\n' | mkfs.ext4 /dev/sda3
	}
	test -b /dev/sda4 && [ "x`head -c5 /dev/sda4`" = "xerase" ] && {
		echo -ne 'y\n' | mkfs.ext4 /dev/sda4
	}
}

boot_hook_add preinit_main do_disk_ready
